package com.qiangqiang.resoldhouse.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qiangqiang.resoldhouse.dto.AgentDTO;
import com.qiangqiang.resoldhouse.dto.PageDTO;
import com.qiangqiang.resoldhouse.entity.Agent;
import com.qiangqiang.resoldhouse.entity.AgentSelect;
import com.qiangqiang.resoldhouse.entity.User;
import com.qiangqiang.resoldhouse.enums.AgentEnums;
import com.qiangqiang.resoldhouse.exception.AgentException;
import com.qiangqiang.resoldhouse.mapper.AgentMapper;
import com.qiangqiang.resoldhouse.mapper.CommentMapper;
import com.qiangqiang.resoldhouse.util.SnowflakeIdWorker;
import com.qiangqiang.resoldhouse.util.TimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.SchemaOutputResolver;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zqh
 * @date: 2018/8/8 15:14
 * @description:
 */
@Service
public class AgentService {

    @Autowired
    private AgentMapper mapper;

    public List<Agent> seleteAllAgent() {
        return mapper.selectList(null);
    }

    //通过id查找DTO
    public AgentDTO findAgentDTOById(Long agentId) {
        Agent agent = mapper.selectById(agentId);
        return beanToDTO(agent);
    }

    //通过id查找
    public Agent findAgentById(Long agentId){
        Agent agent = mapper.selectById(agentId);
        return agent;
    }

    public Boolean updateAgent(Agent agent){
        agent.setUpdateTime(Instant.now().toEpochMilli());
        return mapper.updateById(agent) > 0;
    }

    //通过账号查找DTO
    public Agent findAgentByAccount(String account) {
        Agent agent = mapper.selectAgentIdByAccount(account);
        return agent;
    }

    public AgentDTO beanToDTO(Agent agent) {
        AgentDTO dto = new AgentDTO();
        BeanUtils.copyProperties(agent, dto);
        dto.setUpdateTime(TimeFormat.converTime(agent.getUpdateTime()));
        dto.setRegisterTime(TimeFormat.converTime(agent.getRegisterTime()));
        dto.setCreateTime(TimeFormat.converTime(agent.getCreateTime()));
        return dto;
    }

    //添加经纪人
    public boolean insertAgent(Agent agent) {
        agent.setAgentId(new SnowflakeIdWorker(2, 1).nextId());
        agent.setStatus(false);
        agent.setRank(1.0);
        agent.setCreateTime(Instant.now().toEpochMilli());
        agent.setRegisterTime(Instant.now().toEpochMilli());
        agent.setUpdateTime(Instant.now().toEpochMilli());
        return mapper.insert(agent) > 0;
    }

    //添加删除人by id
    public boolean deleteAgent(Long agentId) {
        Agent agent = mapper.selectById(agentId);
        if (agent == null) {
            throw new AgentException(AgentEnums.AGENT_NOT_EXIST);
        }
        return mapper.deleteById(agentId) > 0;
    }

    //修改房源审核状态
    public boolean passAgent(Long agentId, boolean status) {
        Agent agent = mapper.selectById(agentId);
        agent.setUpdateTime(Instant.now().toEpochMilli());
        if (agent == null) {
            throw new AgentException(AgentEnums.AGENT_NOT_EXIST);
        }
        if (status) {
            agent.setStatus(false);
        } else {
            agent.setStatus(true);
        }
        return mapper.updateById(agent) > 0;
    }


    public PageDTO findPage(Integer pageNum, AgentSelect select) {
        PageDTO<AgentDTO> pageDTO = new PageDTO<>();
        Page<AgentDTO> page = new Page<>(pageNum, 5);
        List<AgentDTO> result = mapper.selectPage(page, getWrapper(select)).stream()
                .map(this::beanToDTO).collect(Collectors.toList());
        pageDTO.setPage(page);
        pageDTO.setResult(result);
        return pageDTO;
    }

    public Wrapper<Agent> getWrapper(AgentSelect select) {
        if (select == null) return null;
        Wrapper<Agent> wrapper = new EntityWrapper<>();
        boolean first = true, has = false;

        //选评分
        if (select.getRank() != null) {
            if (has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for (String a : select.getRank()) {
                if (first) first = false;
                else wrapper = wrapper.or();
                String[] num = a.split("-");
                wrapper = wrapper.between("rank", num[0], num[1]);
            }
        }

        //选城市
        if (select.getCity() != null) {
            if (has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for (String c : select.getCity()) {
                if (!first) wrapper = wrapper.or();
                else first = false;
                wrapper = wrapper.eq("city", c);
            }
        }

        //选状态
        if (select.getStatus() != null) {
            if (has) wrapper = wrapper.andNew();
            has = true;
            first = true;
            for (String c : select.getStatus()) {
                if (!first) wrapper = wrapper.or();
                else first = false;
                wrapper = wrapper.eq("status", c);
            }
        }

        //选名字
        if (select.getAgentName() != null) {
            if (has) wrapper = wrapper.andNew();
            has = true;
            wrapper = wrapper.like("agent_name", select.getAgentName());
        }

        //选择排序方式
        if (!select.getOrder().equals("default"))
            wrapper = wrapper.orderBy(select.getOrder(), false);
        return wrapper;
    }

    /**
     * @param [account]
     * @return boolean
     * @author sky
     * @date 2018/8/13
     * @describe: 根据账号查找经纪人
     */
    public List<Agent> findUserByAccount(String account) {
        return mapper.selectList(new EntityWrapper<Agent>().eq("account", account));
    }

    /**
     * @param [agent]
     * @return boolean
     * @author sky
     * @date 2018/8/13
     * @describe: 验证经纪人
     */
    public boolean validateAgentPassword(Agent agent) {
        List<Agent> list = findUserByAccount(agent.getAccount());
        if (list.size() == 0) {
            return false;
        }
        return agent.getPassword().equals(list.get(0).getPassword());
    }
}
